<template>
  <div>
    <vxe-modal
      v-model="showDicPanel"
      :title="title"
      width="340"
      height="80%"
      class="bk_model no_maximize"
      resize
      :mask="false"
      @close="close"
    >
      <el-container>
        <el-main>
          <el-tabs
            v-model="activeName"
            @tab-click="handleClick"
            class="left_tree_tap"
            type="border-card"
          >
            <el-tab-pane label="常用选项" name="first">
              <vxe-table
              ref='commonTable'
                :show-header="false"
                auto-resize
                size="small"
                stripe
                highlight-current-row
                border="inner"
                highlight-hover-row
                :data="tableData"
                @cell-dblclick="handledbClick"
              >
                <vxe-table-column type="seq" width="40"></vxe-table-column>
                <vxe-table-column :visible='params.multiple' type='checkbox' width="40"></vxe-table-column>
                <vxe-table-column
                  field="name"
                  title="Name"
                ></vxe-table-column> </vxe-table>
              </el-tab-pane>
            <el-tab-pane label="所有选项" name="second">
              <ps-tree ref="dictree" :treeCompData="treeconfig"   @onTreeDblClick="handledbClick"/>
            </el-tab-pane>
            <el-tab-pane name="third">
              <div class="seacher_container" slot="label">
                <vxe-input
                  v-model="orgschval"
                  id="treeSreach"
                  placeholder="快速查询"
                  type="search"
                  style="width: 100%"
                  size="small"
                  @keyup.enter.native="seachTreeQuery"
                  @search-click="seachTreeQuery"
                ></vxe-input>
              </div>
              <vxe-table
              ref='searchTable'
                :show-header="false"
                auto-resize
                size="small"
                stripe
                highlight-current-row
                border="inner"
                highlight-hover-row
                :data="searchtableData"
                @cell-dblclick="handledbClick"
              >
                <vxe-table-column type="seq" width="40"></vxe-table-column>
                <vxe-table-column :visible='params.multiple' type='checkbox' width="40"></vxe-table-column>
                <vxe-table-column
                  field="name"
                  title="Name"
                ></vxe-table-column> </vxe-table>
              </el-tab-pane
            >
          </el-tabs>
        </el-main>
        <el-footer class="vxe_modal_btn">
          <div class="footer_btn">
            <vxe-button type="danger" size="mini" @click="emptyValue">清除</vxe-button>
            <vxe-button type="primary" size="mini" @click="save"
              >确定</vxe-button
            >
            <vxe-button type="danger" size="mini" @click="close"
              >取消</vxe-button
            >
          </div>
        </el-footer>
      </el-container>
    </vxe-modal>
  </div>
</template>
<script>
import psTree from "@/components/psTree/vuePsTree"
import {getRealUrl} from "@/utils/httpRequet";
import request from "@/utils/requestutil"
export default {
  name: "dicPanel",
  components:{
    psTree
  },
  props: {
    callback: {
      type: Function,
      default: () => {
        return null;
      },
    },
    open: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    dickey: {
      type: String,
      default: () => {
        return "";
      },
    },
    params: {
      type: Object,
      default: () => {
        return {};
      },
    },
    value: {
      type: String,
      default: () => {
        return "";
      },
    },
    title: {
      type: String,
      default: () => {
        return "选择";
      },
    },
  },
  data() {
    return {
      loaded:[],
      showDicPanel: false,
      activeName: "first",
      orgschval:"",
      dicvalue: "",
      dicText: "",
      treeconfig:{
        treeBuildConfig:{
          options:{
            check: {
              /**
                 *
                 *   Y 属性定义 checkbox 被勾选后的情况；
                 N 属性定义 checkbox 取消勾选后的情况；
                 "p" 表示操作会影响父级节点；
                 "s" 表示操作会影响子级节点。
                 请注意大小写，不要改变
                 */
              chkboxType: { 'Y': '', 'N': '' },
              enable: true,
            },
            checkType: "check",
          },
          settings:{
            async:{
             autoParam: function(treeid,node){
              return ["id=pid"]
            },
            enable:false,
            dataurl:""
          },
            multiple: false,
            callback:{
              onAsyncSuccess:this.onTreeLoaded
            }
          }
        }
      },
      tableData: [
        
      ],
      searchtableData:[]
    };
  },
  created() {},
  watch: {
     title:{
      handler(val) {

      }
    },
    dickey:{
      handler(val) {
        this.loadData();
      }
    },
    value(val) {
      this.dicvalue = val;
      this.setValue();
    },
    params:{
      handler(val) {
        this.loadData();
      },
      deep:true
    },
    open: {
      handler(val) {
        this.showDicPanel = val;
        if(val){
          this.loaded=[];
          this.loadData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    handledbClick(){
     this.save();
    },
    handleClick(){
      this.loadData();
    },
    seachTreeQuery(){
      request({
        url:"normalDicQuery",
        data:{
          mark:this.dickey,param:this.orgschval
        },
        method:'post'
      }).then(res=>{
        if(res.data){
          this.searchtableData=res.data;
        }
      })
    },
    save() {
      let val=[],text=[],tabledata=[];
      let nodes=[];
      if(this.activeName=='first'){
        let table=this.$refs.commonTable;
        if(this.params.multiple){
          nodes=table.getCheckboxRecords();
        }else{
          nodes.push(table.getCurrentRecord())
        }
      }
      else if(this.activeName=='second'){
        let ztreeObj=this.$refs.dictree.ztreeObj;
        
        if(this.params.multiple){
          nodes = ztreeObj.getCheckedNodes(true);
        }else{
          nodes = ztreeObj.getSelectedNodes();
        }
      }else{
        let table=this.$refs.searchTable;
        if(this.params.multiple){
          nodes=table.getCheckboxRecords();
        }else{
          nodes.push(table.getCurrentRecord())
        }
      }

      for(let i=0;i<nodes.length;i++){
        // if (!nodes[i].isParent || this.dickey=="RS_UN_UM"){
          val.push(nodes[i].key||nodes[i].id);
          text.push(nodes[i].name)
          tabledata.push({id:nodes[i].key||nodes[i].id,name:nodes[i].name})
        // }
      } 
      this.dicvalue =val.join(","),this.dicText=text.join(",");
        if(this.callback)
          this.callback(
            { value: val.join(","), dispalyVal: text.join(",") },
            this.params
          );
        this.tableData.unshift(tabledata)
        request({
          url:getRealUrl("normalDicSave",true,{urlparam:[this.dickey]}),
          voParam:{mark:this.dickey,type:'TREE',id:val.join(","),name:text.join(",")},
          method:'post'
        }).then(res=>{
          if(res.errorCode<0)console.log(res)
          this.close();
        })
    },
    //加载数据
    loadData() {
      if(this.activeName=='second'){
        if(this.loaded.indexOf("second")!=-1)return;
        this.loaded.push("second")
        let config=JSON.parse(JSON.stringify(this.treeconfig));
        config.treeBuildConfig.options.checkType=this.params.multiple?"check":"none"
        config.treeBuildConfig.options.check={enable:this.params.multiple||false,chkboxType: { 'Y': '', 'N': '' }}
        config.treeBuildConfig.settings.multiple=this.params.multiple||false;
        let url=getRealUrl("normalDicTree",true,{urlparam:[this.dickey]});
        let t=this;
        config.treeBuildConfig.settings.async={
          enable:true,
          otherParam:this.dealTreaparam,
          dataFilter: function(treeid,pnode,resdata){
            if(resdata && resdata.length>0){
              let _val=t.value?t.value.split(","):[];
              t.$_.forEach(resdata,(item,val)=>{
                // item.name=item.text;
                // item.pid=item.fid;
                // item.isParent=true;
                 if(item.isParent>0)item.isParent=true
                if(_val.length>0 && _val.indexOf(item.id)!=-1){ 
                  if(t.params.multiple){
                    item.checked=true;
                  }else{
                    setTimeout(function(){
                      let ztreeObj=t.$refs.dictree.ztreeObj;
                      let node=ztreeObj.getNodeByParam("id",item.id)
                      ztreeObj.selectNode(node)
                    },20)
                  }
                  
                }
              })
            }else{
              pnode.isParent=false;
            }
              return resdata;
            },
          url:url
        }
        this.treeconfig=config
      }else if(this.activeName=="first"){
         if(this.loaded.indexOf("first")!=-1)return;
         this.loaded.push("first")
      //加载常用列表
       request({
        url:getRealUrl("normalDicList",true,{urlparam:[this.dickey]})
      }).then(res=>{
        if(res.data){
          this.tableData=res.data;
          this.setValue()
        }else{
          this.tableData=[];
        }
      })
      }else{

      }
    },
    //设置数据
    setValue() {
      if(this.$_.isEmpty(this.value))return;
      let _v=this.value.split(",")
      switch(this.activeName){
        case "first":{ 
          let checkrows=[];
          this.$_.forEach(this.tableData,(row,i)=>{
            if(_v.indexOf(row.id)!=-1){
              if(this.params.multiple){
                checkrows.push(row)
              }else{
                this.$refs.commonTable.setCurrentRow(row)
              }
            }
          })
          if(checkrows.length>0){
            this.$refs.commonTable.setCheckboxRow(checkrows, true)
          }
          break;
        }
        case "third":
          break;
        case "second":{
          if(this.params.multiple==false){

          }
        }
      }
    },
    onTreeLoaded(e,treeid,node,res){
    
    },
    dealTreaparam(treeid,node){
      if(node==undefined){
        return {p0:""}
      }else{
        return {p0:node.id};
      }
    },
    emptyValue(){
      if(this.callback)
      this.callback(
        { value: "", dispalyVal: "" },
        this.params
      );
      this.close();
    },
    close(){
      this.showDicPanel=false;
      this.$emit("update:open",false)
    },
   
  },
};
</script>
<style lang="scss" scoped>
::v-deep
  .left_tree_tap.el-tabs--border-card
  > .el-tabs__header
  .el-tabs__item#tab-third {
  padding: 0 6px !important;
}
.el-footer.vxe_modal_btn {
  border-radius: 0 0 4px 4px;
}
.seacher_container {
  width: 138px;
  height: 38px;
}
</style>
